package com.winchain.provider.expiration.cmd;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.shell.framework.utils.MessageSender;
import com.shell.governor.modules.message.keyword.ExpDlyInsFailedKeyWord;
import com.winchain.chainbill.bill.base.po.CbDfrl;
import com.winchain.chainbill.bill.base.po.CbXfe;
import com.winchain.chainbill.bill.base.service.CbXfeService;
import com.winchain.provider.expiration.exception.ExpDfrlInsException;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.BillExpHldrService;
import com.winchain.provider.expiration.service.BillExpQueryService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpDlyInsMsgCmd implements ICommand<BillExpirationEvent> {
	@Autowired
	private BillExpQueryService billExpQueryService;
	@Autowired
	private CbXfeService cbXfeService;
	@Autowired
	private BillExpHldrService billExpHldrService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		String expDate = ((BillExpirationEvent) context.getSource()).getDate();
		String grpId = ((BillExpirationEvent) context.getSource()).getGrpId();
		List<CbDfrl> dfrls = this.billExpQueryService.selectExpDlyInsBills(expDate, grpId, "2");
		for (CbDfrl dfrl : dfrls) {
			sendPayFailedMessage(dfrl);
		}
		return false;
	}

	private void sendPayFailedMessage(CbDfrl dfrl) {
		String billId = dfrl.getBillId();
		String finId = this.billExpHldrService.getFinId(billId);
		ExpDlyInsFailedKeyWord keyWord = getExpDlyInsFailedKeyWord(dfrl);
		try {
			MessageSender.sendMessageByTmpl(SpringContextUtil.getProperty("system.code"), "MT03106", keyWord, finId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExpDfrlInsException(e.getMessage(), e);
		}
	}

	private ExpDlyInsFailedKeyWord getExpDlyInsFailedKeyWord(CbDfrl dfrl) {
		CbXfe xfe = (CbXfe) this.cbXfeService.selectByKey(dfrl.getXfeId());

		ExpDlyInsFailedKeyWord keyWord = new ExpDlyInsFailedKeyWord();
		keyWord.setExpDate(DateUtil.parseDate(dfrl.getExpDate(), "yyyyMMdd", "yyyy-MM-dd"));
		keyWord.setBillAmt(String.valueOf(dfrl.getDfrInt()));
		keyWord.setCusName(xfe.getBuyerNm());
		return keyWord;
	}
}
